package com.neko.Thread_Learning;

/**
 * 模拟【龟兔赛跑】
 * class t5_2_thread_Race == class Race
 * */
public class t5_2_thread_Race implements Runnable {

    // 胜利者
    private static String winner;

    @Override
    public void run() {
        for (int i=1; i<=100; i++) {

            if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0 ) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 调用 gameOver(..)
            boolean flag = gameOver(i);

            // 如果【比赛结束了】, 就停止程序
            if (flag) {
                break;
            }

            System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
        }
    }


    // 判断【是否完成 比赛】
    private boolean gameOver(int steps) {

        // 判断【是否有 胜利者】
        if (winner != null) {   // 若已经存在【胜利者】
            return true;

        } { // else 可以 缺少
            if (steps == 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner is " + winner);
                return true;
            }
        }

        return false;
    }


    /**
     * Main
     * */
    public static void main(String[] args) {

        t5_2_thread_Race race = new t5_2_thread_Race();

        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();

    }




}
